package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.service.ClothingProductService;
import com.graduation.springbootinit.service.ShoppingCartService;
import com.graduation.springbootinit.service.StoreService;
import com.graduation.springbootinit.mapper.ShoppingCartMapper;
import com.graduation.springbootinit.mapper.ShoppingCartItemMapper;
import com.graduation.springbootinit.model.entity.ShopPart.ClothingProduct;
import com.graduation.springbootinit.model.entity.ShopPart.ShoppingCart;
import com.graduation.springbootinit.model.entity.ShopPart.ShoppingCartItem;
import com.graduation.springbootinit.model.vo.ShoppingCartItemVO;
import com.graduation.springbootinit.model.vo.StoreCartGroupVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper cartMapper;

    @Resource
    private ShoppingCartItemMapper cartItemMapper;

    @Resource
    private ClothingProductService productService;

    @Resource
    private StoreService storeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> addToCart(Long userId, ShoppingCartItem cartItem) {
        // 1. 校验商品是否存在
        ClothingProduct product = productService.getById(cartItem.getProductId());
        if (product == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }
        
        // 2. 获取或创建购物车
        ShoppingCart cart = getOrCreateCart(userId);
        cartItem.setCartId(cart.getId());
        cartItem.setStoreId(product.getStoreId());
        
        // 3. 查找购物车中是否已存在该商品的该尺码
        QueryWrapper<ShoppingCartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cart_id", cart.getId())
                   .eq("product_id", cartItem.getProductId())
                   .eq("size", cartItem.getSize());
        
        ShoppingCartItem existItem = cartItemMapper.selectOne(queryWrapper);
        
        if (existItem != null) {
            // 4.1 已存在则更新数量
            existItem.setQuantity(existItem.getQuantity() + cartItem.getQuantity());
            cartItemMapper.updateById(existItem);
        } else {
            // 4.2 不存在则新增
            cartItem.setSelected(1);
            cartItemMapper.insert(cartItem);
        }
        
        return ResultUtils.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> updateQuantity(Long userId, ShoppingCartItem cartItem) {
        // 直接用id更新数量
        ShoppingCartItem existItem = cartItemMapper.selectById(cartItem.getId());
        if (existItem == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }
        
        existItem.setQuantity(cartItem.getQuantity());
        cartItemMapper.updateById(existItem);
        return ResultUtils.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> removeFromCart(Long userId, ShoppingCartItem cartItem) {
        // 直接用id删除
        cartItemMapper.deleteById(cartItem.getId());
        return ResultUtils.success(true);
    }

    @Override
    public BaseResponse<List<ShoppingCartItemVO>> listUserCartItems(Long userId) {
        // 1. 获取用户购物车
        ShoppingCart cart = getCart(userId);
        if (cart == null) {
            return ResultUtils.success(new ArrayList<>());
        }
        
        // 2. 查询购物车商品
        List<ShoppingCartItemVO> itemVOs = cartItemMapper.selectCartItems(cart.getId());
        
        return ResultUtils.success(itemVOs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> updateSelected(Long userId, ShoppingCartItem cartItem) {
        // 直接用id更新选中状态
        ShoppingCartItem existItem = cartItemMapper.selectById(cartItem.getId());
        if (existItem == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }
        
        existItem.setSelected(cartItem.getSelected());
        cartItemMapper.updateById(existItem);
        return ResultUtils.success(true);
    }

    @Override
    public List<ShoppingCartItemVO> getCartItemsByIds(List<Long> cartItemIds) {
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            return new ArrayList<>();
        }
        return cartItemMapper.selectCartItemsByIds(cartItemIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Long> cartItemIds) {
        if (cartItemIds != null && !cartItemIds.isEmpty()) {
            cartItemMapper.deleteBatchIds(cartItemIds);
        }
    }

    @Override
    public List<ShoppingCartItemVO> getSelectedItems(Long cartId) {
        QueryWrapper<ShoppingCartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cart_id", cartId)
                    .eq("selected", 1);  // 只获取已选中的商品
        
        return cartItemMapper.selectCartItemsByCartId(cartId);
    }

    @Override
    public BaseResponse<List<StoreCartGroupVO>> listUserCartItemsByStore(Long userId) {
        // 1. 获取用户的所有购物车商品
        BaseResponse<List<ShoppingCartItemVO>> response = listUserCartItems(userId);
        if (response.getCode() != 0 || response.getData() == null) {
            return ResultUtils.error(response.getCode(), response.getMessage());
        }
        List<ShoppingCartItemVO> allItems = response.getData();

        // 2. 过滤掉storeId为null的项，并按商户ID分组
        Map<Long, List<ShoppingCartItemVO>> storeGroups = allItems.stream()
                .filter(item -> item.getStoreId() != null)  // 添加过滤条件
                .collect(Collectors.groupingBy(ShoppingCartItemVO::getStoreId));

        // 3. 构建返回结果
        List<StoreCartGroupVO> result = new ArrayList<>();
        for (Map.Entry<Long, List<ShoppingCartItemVO>> entry : storeGroups.entrySet()) {
            Long storeId = entry.getKey();
            if (storeId != null) {  // 再次确保storeId不为null
                StoreCartGroupVO storeGroup = new StoreCartGroupVO();
                storeGroup.setStoreId(storeId);
                // 获取店铺名称
                String storeName = storeService.getStoreNameById(storeId);
                if (storeName != null) {  // 确保店铺名称不为null
                    storeGroup.setStoreName(storeName);
                    storeGroup.setCartItems(entry.getValue());
                    result.add(storeGroup);
                }
            }
        }

        return ResultUtils.success(result);
    }

    /**
     * 获取用户购物车
     */
    public ShoppingCart getCart(Long userId) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return cartMapper.selectOne(queryWrapper);
    }

    /**
     * 获取或创建用户购物车
     */
    public ShoppingCart getOrCreateCart(Long userId) {
        ShoppingCart cart = getCart(userId);
        if (cart == null) {
            cart = new ShoppingCart();
            cart.setUserId(userId);
            cartMapper.insert(cart);
        }
        return cart;
    }

    @Override
    public Long getCartId(Long userId) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        ShoppingCart cart = cartMapper.selectOne(queryWrapper);
        if (cart == null) {
            return null;
        }
        return cart.getId();
    }
} 
